package com.chengxiaoxiao.ai_demo.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * Mybatis自动填充
 *
 * @Description:
 * @Author Cheng Xiaoxiao
 * @Date: 2025/3/12 17:11
 */
public class PxMetaObjectHandler implements MetaObjectHandler {

    public static final String FIELD_DELETE_STATUS = "deleteStatus";
    public static final String FIELD_CREATE_TIME = "createTime";
    public static final String FIELD_UPDATE_TIME = "updateTime";

    /**
     * 使用mp实现添加操作，这个方法执行
     *
     * @param metaObject 填充的对象类型
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 1.判断是否开启
        // 2.判断对象是否存在此Setter
        // 3.判断用户是否已经设置

        // 1) 逻辑删除
        if (metaObject.hasSetter(FIELD_DELETE_STATUS)) {
            Class<?> getterType = metaObject.getGetterType(FIELD_DELETE_STATUS);
            if (getterType.equals(Boolean.class)) {
                //Boolean 处理
                this.strictInsertFill(metaObject, FIELD_DELETE_STATUS,
                        () -> false, Boolean.class);
            } else if (getterType.equals(Integer.class)) {
                // Integer处理
                this.strictInsertFill(metaObject, FIELD_DELETE_STATUS,
                        () -> 0, Integer.class);
            }
        }

        // 2) 创建时间
        if (metaObject.hasSetter(FIELD_CREATE_TIME)) {
            this.strictInsertFill(metaObject, FIELD_CREATE_TIME, Date.class, new Date());
        }

        // 3) 更新时间
        if (metaObject.hasSetter(FIELD_UPDATE_TIME)) {
            this.strictInsertFill(metaObject, FIELD_UPDATE_TIME, Date.class, new Date());
        }
    }

    /**
     * 使用mp实现修改操作，这个方法执行
     *
     * @param metaObject 填充对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 修改更新时间
        if (metaObject.hasSetter(FIELD_UPDATE_TIME)) {
            this.strictInsertFill(metaObject, FIELD_UPDATE_TIME, Date.class, new Date());
        }
    }
}
